#!/usr/bin/env node

const fs = require('fs')
const path = require('path')
const fse = require('fs-extra')

const inquirer = require('inquirer')
const ejs  = require('ejs')

const readDirRecursive = require('./utils/fs-read-recursive')

executor()

async function executor() {
    const anwsers = await question()
    const tplDir = path.join(__dirname, 'template')
    const destDir = process.cwd()
    const files = readDirRecursive(tplDir, () => true)

    files.forEach(file => {
        console.log(path.join(tplDir, file))
        ejs.renderFile(path.join(tplDir, file), anwsers, (err, result) => {
            if (err) throw err
            let fileArr = path.join(destDir, file).split('/')
            fse.mkdirpSync(fileArr.slice(0, fileArr.length - 1).join('/'))
            fs.writeFileSync(path.join(destDir, file), result)
        })
    })
}

function question() {
    return inquirer.prompt([
            {
                type: 'input',
                name: 'projectName',
                message: 'Project name?'
            }
        ])
}

// 递归读取文件夹下的文件
function _ReadDir(PATH, anwsers, dest) {
    console.log(anwsers, dest)
    fs.readdir(PATH, (err, files) => {
        if (err) throw err
        files.forEach(file => {
            let filePath = path.join(PATH, file)
            fs.stat(filePath, (err, stat) => {
                if (stat.isFile()) {
                    console.log(PATH, filePath, file)
                    // 写入文件
                } else {
                    _ReadDir(filePath)
                }
            })
        })
    })
}